<template>
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :configTable="configTable"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls" slot-scope="props">
        <!-- <el-button size="small" type="primary" @click="addHandle">新增</el-button> -->
        <multiuse-button size="small" type="primary" :click="addHandle" :auth-list="auths" auth-mark="/api/information/materiel/save">新增</multiuse-button>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <newsModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>

  </div>
</template>

<script>
import {
  queryNews,
  tcCodeList,
  saveNews,
  deleteNews,
  releaseNews,
  revokeNews,
 } from '@/api/community/news/index';
import { dictionary } from '@/utils/dictMixin';
import { addDate } from '@/utils/index';
import newsModal from './newsModal';
import { authority } from '@/utils/authMixin';
import Cookies from 'js-cookie';
export default {
  name: 'news',
  mixins: [dictionary,authority],
  components: {
    newsModal
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      configTable: {pageSize:10},
      visible: false,
      dialogTitle: '',
      fetchApi: queryNews,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '详情', release: '发布', undo: '撤销', delete: '删除' }
    };
  },
  methods: {
    init(){
      let dataType = Cookies.get('dataType');
      if (dataType === '10461001') {
        this.columns.push({
          title: '数据来源',
          dataIndex: 'dataSource',
          align: 'center',
        })
      }
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '标题',
          fieldName: 'title',
          placeholder: '标题'
        },
        {
          type: 'SELECT',
          label: '发布状态',
          fieldName: 'status',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '创建时间',
          fieldName: 'createTime',
          placeholder: '创建时间',
          // dateType: 'datetimerange'
        },
      ];
    },
    createTableColumns() {
      let dataType = Cookies.get('dataType');
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 220,
          fixed: 'left',
          render: (props, h) => {
            let isDisabled = dataType === '10461001'&&props.row.dataSource === '主机厂'?true:false;
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  查看
                </el-button>
                <multiuse-button size="mini" disabled={isDisabled} divider="before" containerStyle={props.row.publishStatus == '已发布' ? {color:'#D9D9D9'}:{}} type="text" onClick={() => this.editHandle(props.row)} auth-list={this.auths} auth-mark={'/api/information/materiel/save'}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" disabled={isDisabled} divider="before" containerStyle={props.row.publishStatus == '已发布' ? {color:'#D9D9D9'}:{}} type="text" onClick={() => this.handleOnline(props.row)} auth-list={this.auths} auth-mark={'/api/information/materiel/release?id=${id}'}>
                  发布
                </multiuse-button>
                <multiuse-button size="mini" disabled={isDisabled} divider="before" type="text" onClick={() => this.handleRevoke(props.row)} auth-list={this.auths} auth-mark={'/api/information/materiel/revoke?id=${id}'}>
                  撤销
                </multiuse-button>
                <multiuse-button size="mini" disabled={isDisabled} divider="before" containerStyle={props.row.publishStatus == '已发布' ? {color:'#D9D9D9'}:{}} type="text" onClick={ ()=>this.handleDelete(props.row) } auth-list={this.auths} auth-mark={'/api/information/materiel/delete?id=${id}'}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '标题',
          dataIndex: 'title',
          minWidth: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span class="long-title">{props.row.title}</span>;
          }
        },
        {
          title: '内容类型',
          dataIndex: 'contentType',
          sorter: true,
          align: 'center',
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editType: 'select',
          editItems: [],
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '发布状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: [],
          editType: 'select',
          editItems: [],
          /*render: props => {
            let val;
            switch (props.row.status) {
              case 20211001:
                val = "未发布"
                break;
              case 20211002:
                val = "已发布"
                break;
              case 20211003:
                val = "已撤销"
                break;
            }
            return <span>{val}</span>;
          }*/
        },
      ];
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    editHandle(row) {
      if(row.publishStatus == "已发布"){
        this.$message.info("请先撤销后再进行编辑！");
        return false
      } else {
        this.handleType = 'edit';
        this.formData = row;
        this.showHandler();
      }
    },
    showHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    // 发布弹框
    handleOnline(row) {
      // log('发布数据', row)
      if(row.publishStatus == '已发布'){
        this.$message.info("状态为已发布的内容不可进行发布！");
        return false
      } else{
        this.$confirm(
          '<p>1. 本平台不对用户发布的任何内容(包括但不限于文章、图片、视频)的准确性进行保证。</p><p>2. 用户需对所发表的内容负责，因所发表内容引发的一切纠纷，由该内容的发表者承担全部法律及连带责任。</p>',
          '免责声明', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '同意并发布',
          cancelButtonText: '取消',
          center: true
        }).then(() => {
          releaseNews(row.id).then((res) => {
            if(res.resultCode == 200){
              this.$message.success("发布成功");
              this.changeHandle();
            } else {
              this.$message.error(res.errMsg);
              return false
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消发布'
          });
        });
      }
    },
    // 撤销
    handleRevoke(item) {
      if(item.publishStatus == '已撤销' || item.publishStatus == '未发布' ){
        this.$message.info("状态为“未发布、已撤销”的不可以进行撤销");
        return false
      } else{
        this.$confirm('确定要撤销吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(()=>{
          let id=item.id
          revokeNews(id).then(() => {
            this.$message.success("撤销成功！");
            item.revokeVisible = false;
            this.changeHandle();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消撤销'
          })
        })
      }
    },
    // 删除
    handleDelete(item) {
      if(item.publishStatus == '已发布'){
        this.$message.info("请先撤销后再进行删除！");
        return false
      } else {
        this.$confirm('确定要删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(()=>{
          let id=item.id
          deleteNews(id).then(() => {
            this.$message.success("删除成功！");
            item.delVisible = false;
            this.changeHandle();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      // const index = this.list.indexOf(row);
      //  this.list.splice(index, 1);
      }
    },
    showHandler() {
      this.dialogTitle = this.conf[this.handleType];
      this.visible = true;
    },
    changeHandle(val) {
      if (!val) {
        val = {createTime:[]}
      }
      this.fetchParams = Object.assign({
        createdStarTime:val.createTime[0]||undefined,
        createdEndTime:val.createTime[1] ? val.createTime[1]:undefined,
        // createdEndTime:val.createTime[1] ? addDate(val.createTime[1]):undefined,
      }, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getPostStatusList() {
      const res = await tcCodeList('2020');
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='status').itemList = this.columns[5].filterItems = this.columns[5].editItems = res.data.map(x => ({ value: x.codeId, text: x.codeCnDesc }));
      }
    },
    async getContentTypeList() {
      const res = await tcCodeList('2014');
      if (res.resultCode === 200) {
        this.columns[3].filterItems = this.columns[3].editItems = res.data.map(x => ({ value: x.codeId, text: x.codeCnDesc }));
      }
    },
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.init()
    this.getPostStatusList()
    this.getContentTypeList()
  },
  filters: {
    formatDate: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == "") {
        return "";
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + "-" + month + "-" + day;
    }
  }
};
</script>

<style lang="less" scoped>
</style>
